// 获取应用实例
const app = getApp()

Page({

    data: {
        list_data: [],
        now_page: 0,
        list_total: 0,
        keywords: '',
        limit: 20,
        table_or_card: 1,
        table_scroll_left: 0,
        left_head_style: "",
        table_head_style: "",
        table_content_style: "",
        max_box_style: "",
        keywords_template_no:"",
        content_header_show: true,
        choose_supplier_name: '',
        allchecked:false,
        check_status:[
          "未审核",
          "已审核",
        ],
        check_num:0,
        table_head: [
          // {id: 1, name: '图片', field: 'images', is_checked: false, width: 70, show_user: [0]},
          // {id: 2, name: '简码', field: 'template_no', is_checked: false, width: 100, show_user: [0]},
         
          {id: 6, name: '供应商', field: 'supply_name', is_checked: true, width: 170, show_user: [0,2,3]},
          {id: 8, name: '采购日期', field: 'purchase_time', is_checked: true, width: 180, show_user: [0,1,2,3]},
          {id: 4, name: '采购员', field: 'admin.realname', is_checked: true, width: 120, show_user: [0,1]},
          {id: 3, name: '单号', field: 'caigou_id', is_checked: true, width: 170, show_user: [0,1,2,3]},
          {id: 5, name: '到料状态', field: 'reviced_status', is_checked: true, width: 140, show_user: [0,1,3]},
          {id: 6, name: '审核状态', field: 'Posted', is_checked: true, width: 150, show_user: [0,1]},
          {id: 7, name: '最后修改', field: 'last_save', is_checked: true, width: 300, show_user: [0,1]},
          {id: 9, name: '最后审核', field: 'last_audit', is_checked: true, width: 300, show_user: [0,1]},
        ],
    },
    bindPickerChange: function(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      this.setData({
        Posted: e.detail.value,
        now_page:0,
      })
      this.get_list_data(1);
    },
    onLoad() {
        wx.setNavigationBarTitle({
            title: '物料采购'
        });
        // 获取列表数据
        this.get_list_data();
    },

    // 页面触底时执行
    onReachBottom: function () {
        this.get_list_data();
    },
    tr_boxs_scroll_end: function (e) {
      var __this = this;
      setTimeout(function () {
          __this.setData({
              table_scroll_left: e.detail.scrollLeft
          });
      }, 180);
  },
    all_purchase_delete(){
      let list_data = this.data.list_data;
      const filteredIds = list_data.filter(obj => obj.checked === true).map(obj => obj.purchase_id);
      if(filteredIds.length<1){
          wx.showToast({
            title: '请先选择采购单',
            icon: 'none',
            duration: 1000,
        });
        return ;
      }

      var res = app.request_api('/admin/purchase/del',{ids:filteredIds});
      res.then(res => {
        wx.showToast({
            title: '删除成功',
            icon: 'none',
            duration: 2000,
        });
        filteredIds.forEach((v,k)=>{
          let index = list_data.findIndex(res=>res.purchase_id==v);
          if(index!=-1){
            list_data.splice(index,1)
          }
        })
        this.setData({
            list_data:list_data
        })
    });
      console.log('list_data',list_data)
    },
    //审核按钮点击
    purchase_check:function(){
        let list_data = this.data.list_data;
        const filteredIds = list_data.filter(obj => obj.checked === true).map(obj => obj.purchase_id);
        if(filteredIds.length<1){
          wx.showToast({
            title: '请先选择采购单',
            icon: 'none',
            duration: 1000,
        });
        return ;
        }
        var res = app.request_api('/admin/purchase/approval',{ids:filteredIds});
        res.then(res => {
          wx.showToast({
              title: '审核成功',
              icon: 'none',
              duration: 2000,
          });
          filteredIds.forEach((v,k)=>{
            let index = list_data.findIndex(res=>res.purchase_id==v);
            if(index!=-1){
              list_data[index].checked=false;
              
              list_data[index].Posted=1;
            }
          })
          this.setData({
              list_data:list_data
          })
      });
        console.log(filteredIds)
    },
    // 监听页面滚动
    onPageScroll: function (e) {
      // console.log(e)
      // if (e.scrollTop > 0 && this.data.table_or_card == 1) {
      //     this.setData({
      //         table_head_style: "position: fixed;top: 0;z-index: 82;background:#ffffff;width:calc(100vw - (265vmin / 7.5));",
      //         left_head_style: "position: fixed;top: 0;z-index: 82;width:calc(200vmin / 7.5);",
      //         table_content_style: "margin-top: calc(10vmin / 7.5);",
      //         content_header_show: false,
      //         max_box_style: "margin-top: calc(70vmin / 7.5);",
      //     })
      // } else {
      //     this.setData({
      //         table_head_style: "",
      //         table_content_style: "",
      //         left_head_style: "",
      //         max_box_style: "",
      //         content_header_show: true
      //     })
      // }

      if (this.data.table_or_card == 2) {
          return false;
      }
      // 如果回到顶部则显示头部搜索
      if (e.scrollTop == 0) {
          this.setData({
              table_head_style: "",
              table_content_style: "",
              left_head_style: "",
              max_box_style: "",
              content_header_show: true
          });
          return false;
      }
      // 如果不在顶部则固定表头并隐藏头部
      if (this.data.content_header_show) {
          this.setData({
              table_head_style: "position: fixed;top: 0;z-index: 82;background:#ffffff;width:calc(100vw - (265vmin / 7.5));",
              left_head_style: "position: fixed;top: 0;z-index: 82;width:calc(200vmin / 7.5);",
              table_content_style: "margin-top: calc(10vmin / 7.5);",
              content_header_show: false,
              max_box_style: "margin-top: calc(70vmin / 7.5);",
          })
      }
    },
    // 监听下拉[刷新]
    onPullDownRefresh: function () {
        this.setData({
            list_data: [],
            now_page: 0,
            list_total: 0,
            keywords: '',
        });
        // 获取列表
        this.get_list_data();
        // 停止下拉
        setTimeout(() => {
            wx.stopPullDownRefresh();
        }, 1000)
    },
   // 切换表格或者卡片
   changeTableOrCard: function () {
    var table_or_card = 2;
    if (this.data.table_or_card == 2) {
        table_or_card = 1;
    }
    // 清空数据 重新请求 防止多数据时切换慢
    this.setData({
        table_or_card: table_or_card,
        buy_list: [],
        now_page: 0,
        list_total: 0,
    });
    // this.get_buy_list();
},
    // 获取数据
    get_list_data: function (is_search = 0) {
        var __this = this;
        // 验证
        if ((this.data.list_data.length >= this.data.list_total) && this.data.now_page > 0) {
          console.log('a')
            return false;
        }
        let search = [];
        let item={}

        if(this.data.keywords_template_no!==''){
          let item={}
          item.field = 'template_no';
          item.val = this.data.keywords_template_no;
          item.operator = 'false';
          search.push(item)
        }
        if(this.data.Posted!==''){
          let item={}
          item.field = 'Posted';
          item.val = this.data.Posted;
          item.operator = '=';
          search.push(item)
        }
 


        // 请求参数
        var req_param = {
            page: this.data.now_page + 1,
            quick_search: __this.data.keywords,
            limit: __this.data.limit,
            search,
        };
        // 发起请求
        var result = app.request_api('admin/Purchase/index', req_param);
        // 处理结果
        result.then(res => {
            console.log(res)
            // 如果是搜索
            if (is_search == 1) {
                this.setData({
                    list_data: [],
                    list_total: 0,
                    now_page: 0
                })
            }
            res.list.forEach(function(v,k) {
              v.checked=false
            })
            // 重设
            this.setData({
                list_data: this.data.list_data.concat(res.list),
                list_total: res.total,
                now_page: this.data.now_page + 1
            });
        });
    },
    checkboxChange2: function (event) {
      const values = event.detail.value;
      const list_data = this.data.list_data.map(item => {
          if(values.includes('all')){
            item.checked = true;
          }else{
            item.checked = false;
          }
        return item;
      });
      values.includes('all')
      var check_num = list_data.reduce((num,v)=>{
        if(v.Posted==1 && v.checked==true){
          return num+1;
        }else{
          return num;
        }
      },0)
      this.setData({check_num, list_data ,allchecked:values.includes('all')});
    },
    checkboxChange: function (event) {
      const values = event.detail.value;
      const list_data = this.data.list_data.map(item => {
          item.checked = values.includes(String(item.purchase_id));
        return item;
      });
      var check_num = list_data.reduce((num,v)=>{
        if(v.Posted==1 && v.checked==true){
          return num+1;
        }else{
          return num;
        }
      },0)
      this.setData({check_num, list_data });
    },
    // 搜索
    GoSearch: function (events) {
        var keywords = events.detail.value.trim();
        this.setData({
            keywords: keywords,
            list_data: [],
            now_page: 0,
            list_total: 0,
        });
        this.get_list_data(1);
    },

        // 搜索
        TemplateNoSearch: function (events) {
          var keywords = events.detail.value.trim();
          this.setData({
              keywords_template_no: keywords,
              list_data: [],
              now_page: 0,
              list_total: 0,
          });
          this.get_list_data(1);
      },

    // 新建物料采购单
    purchase_add: function (events) {
        var __this = this;
        wx.navigateTo({
            url: '/pages/purchase_add/purchase_add',
            events: {
                // 当添加完成时
                changeData: function (data) {
                    // 重新请求数据
                    __this.setData({
                        list_data: [],
                        now_page: 0,
                        list_total: 0,
                    });
                    __this.get_list_data();
                }
            }
        });
    },

    // 修改采购单
    purchase_update: function (events) {
        var __this = this;
        var index = events.currentTarget.dataset.index;
        var purchase_id = this.data.list_data[index].purchase_id;
        // 跳转页面
        wx.navigateTo({
            url: '/pages/purchase_add/purchase_add?purchase_id=' + purchase_id,
            events: {
                // 当添加完成时
                changeData: function (data) {
                    // 重新请求数据
                    __this.setData({
                        list_data: [],
                        now_page: 0,
                        list_total: 0,
                    });
                    __this.get_list_data();
                }
            }
        });
    },

    // 跳转到报单详情
    purchase_detail: function (events) {
        var __this = this;
        var index = events.currentTarget.dataset.index;
        var purchase_id = this.data.list_data[index].purchase_id;
        var purchase_sn = this.data.list_data[index].purchase_sn;
        // 跳转页面
        wx.navigateTo({
            url: '/pages/purchase_detail/purchase_detail?purchase_id=' + purchase_id + '&purchase_sn=' + purchase_sn,
            events: {
                // 删除
                DeleteData: function (data) {
                    // 将此数据从列表删除
                    __this.data.list_data.splice(index, 1);
                    __this.setData({
                        list_data: __this.data.list_data
                    });
                },
                // 审核
                AuditData: function (data) {
                    __this.data.list_data[index].Posted = 1;
                    __this.setData({
                        list_data: __this.data.list_data
                    })
                },
                // 反审
                ReverseData: function (data) {
                    __this.data.list_data[index].Posted = 0;
                    __this.setData({
                        list_data: __this.data.list_data
                    })
                },
            }
        });
    },

    // 删除采购单
    purchase_delete: function (events) {
        var __this = this;
        var index = events.currentTarget.dataset.index;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要删除吗',
            success(res) {
                if (res.confirm) {
                    __this.purchase_delete_request(index);
                }
            },
        });
    },

    // 删除采购单请求
    purchase_delete_request: function (index) {
        var __this = this;
        var purchase_id = __this.data.list_data[index].purchase_id;
        var result = app.request_api('admin/purchase/del', {
            ids: [purchase_id]
        }, true);
        result.then(res => {
            wx.showToast({
                title: '删除成功',
                icon: 'none',
                duration: 2000,
            });
            // 将此数据从列表删除
            __this.data.list_data.splice(index, 1);
            __this.setData({
                list_data: __this.data.list_data
            });
        });
    },

    // 审核
    purchase_audit: function (events) {
        var __this = this;
        var index = events.currentTarget.dataset.index;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要审核通过吗',
            success(res) {
                if (res.confirm) {
                    __this.purchase_audit_request(index);
                }
            },
        });
    },

    // 审核请求
    purchase_audit_request: function (index) {
        var __this = this;
        var purchase_id = __this.data.list_data[index].purchase_id;
        var result = app.request_api('admin/purchase/approval', {
            ids: [purchase_id]
        }, true);
        result.then(res => {
            wx.showToast({
                title: '审核成功',
                icon: 'none',
                duration: 2000,
            });
            __this.data.list_data[index].Posted = 1;
            __this.setData({
                list_data: __this.data.list_data
            })
        });
    },

    // 反审
    purchase_reverse: function (events) {
        var __this = this;
        var index = events.currentTarget.dataset.index;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要反审吗',
            success(res) {
                if (res.confirm) {
                    __this.purchase_reverse_request(index);
                }
            },
        });
    },

    // 反审请求
    purchase_reverse_request: function (index) {
        var __this = this;
        var purchase_id = __this.data.list_data[index].purchase_id;
        var result = app.request_api('admin/purchase/against', {
            ids: [purchase_id]
        }, true);
        result.then(res => {
            wx.showToast({
                title: '反审成功',
                icon: 'none',
                duration: 2000,
            });
            __this.data.list_data[index].Posted = 0;
            __this.setData({
                list_data: __this.data.list_data
            })
        });
    },




})